#include <stdio.h>
#include <string>
#include <PopupLoggerUI.hpp>

using namespace PopupUtils;

LoggerUI *LoggerUI::staticLogger = 0;

#define POPUP_GEN_LOG_FUNCTION(__name__, __level__)             \
  void __name__(const char *p_format, ...) {                   \
    if (LoggerUI::instance() == 0) {                            \
        LoggerUI::init(new DefaultLogger());                    \
    }                                                           \
    va_list _args;                                              \
    va_start(_args, p_format);                                  \
    LoggerUI::instance()->logmsg(__level__, p_format, _args);   \
    va_end(_args);                                              \
  }                                                             \
  void __name__(const std::string & p_msg) {                   \
    __name__(p_msg.c_str());                                    \
  }

POPUP_GEN_LOG_FUNCTION(PopupUtils::trace,    POPUP_LOG_TRACE)
POPUP_GEN_LOG_FUNCTION(PopupUtils::info,     POPUP_LOG_INFO)
POPUP_GEN_LOG_FUNCTION(PopupUtils::warning,  POPUP_LOG_WARNING)
POPUP_GEN_LOG_FUNCTION(PopupUtils::error,    POPUP_LOG_ERROR)
POPUP_GEN_LOG_FUNCTION(PopupUtils::critical, POPUP_LOG_CRITICAL)

void DefaultLogger::logmsg(LogLevel p_level,
                             const char *p_format,
                             va_list p_args)
{
  char log[1024];
  vsprintf(log, p_format, p_args);
  printf("[%s] %s\n", convertLogLevelToString(p_level), log);
}

const char *PopupUtils::convertLogLevelToString(LogLevel p_level)
{
  switch (p_level) {
  case POPUP_LOG_TRACE:
    return "TRACE";
  case POPUP_LOG_INFO:
    return "INFO";
  case POPUP_LOG_WARNING:
    return "WARNING";
  case POPUP_LOG_ERROR:
    return "ERROR";
  case POPUP_LOG_CRITICAL:
    return "CRITICAL";
  default:
    return "UNKNOWN";
  }
}
